import time
current_milli_time = lambda: int(round(time.time() * 1000))

#!python3

import curses

menu = ["Run", "Exit"]


def menuselect(stdscr, menu, num):
	for x in range(len(menu)):
		if x == num:
			stdscr.addstr(3 + x, 0, menu[x], curses.A_STANDOUT)
		else:
			stdscr.addstr(3 + x, 0, menu[x])
	stdscr.refresh()

def startprogram(stdscr,currentnum):
	height,width = stdscr.getmaxyx()
	start_time = current_milli_time()
	number = 1000000
	cache = [None]*(number+1)
	largest = 2
	for x in range(2,number+1):
		length = 1
		current = x
		
		stdscr.move(height-1, 0)
		stdscr.clrtoeol()
		stdscr.addstr(height-1, 0, str(x))
		stdscr.refresh()
		
		while(current > 1):
			if current < x:
				length = length + cache[current] - 1
				break
			elif((current % 2) == 0):
				current = int(current / 2)
				length = length + 1
			else:
				current = (current * 3) + 1
				length = length + 1
		cache[x] = length
		if length > cache[largest]:
			largest = x
	
	stdscr.move(height-1, 0)
	stdscr.clrtoeol()
	stdscr.addstr(height-2, 0, "Answer: "+str(largest)+" at "+str(cache[largest])+" iterations")
	stdscr.addstr(height-1, 0, "Time: "+str(current_milli_time()-start_time)+"ms")
	stdscr.refresh()
	stdscr.getch()
  
currentnum = 0
stdscr = curses.initscr()
#curses.start_color()
#curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)

curses.noecho()
curses.cbreak()
curses.curs_set(0)
stdscr.keypad(1)

stdscr.addstr(0, 0, "Welcome to PiPal!\n\n\n")
stdscr.refresh()

menuselect(stdscr, menu, currentnum)

while 1:
	c = stdscr.getch()
	if c == curses.KEY_DOWN:
		currentnum = currentnum + 1
		if currentnum == len(menu):
			currentnum = currentnum - 1
		menuselect(stdscr, menu, currentnum)
	elif c == curses.KEY_UP:
		currentnum = currentnum - 1
		if currentnum < 0:
			currentnum = 0
		menuselect(stdscr, menu, currentnum)
	elif c == ord('q'):
		break  # Exit the while()
	elif c == ord("\n"):
		if currentnum == 1:
			break
		startprogram(stdscr,currentnum)


#reverse curses settings
curses.nocbreak()
stdscr.keypad(0)
curses.echo()

#end the curses session
curses.endwin()